package com.ecsolutions.controller;

import com.ecsolutions.entity.ApplySerial_Entity;
import com.ecsolutions.entity.User_Entity;
import com.ecsolutions.service.AmountDeal_Service;
import com.ecsolutions.service.ApplySerial_Service;
import com.ecsolutions.service.User_Service;
import com.ecsolutions.soaClient.WorkFlowServiceManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ApplySerial_Controller {
    private String insert_result; //check insert

    @Autowired
    public WorkFlowServiceManager workFlowService;

    @Autowired
    public ApplySerial_Service applySerial_service;

    @Autowired
    public AmountDeal_Service amountDeal_service;

    @Autowired
    public User_Service user_service;

    private String operatorId = "1";
    private String custcode = "000000";
    private String operatorBank = "1Y0";
    @GetMapping("/ApplySerial")
    public String getApplySerial(Model model, @RequestParam("custcode") String custcode) {
        this.custcode = custcode;

        ApplySerial_Entity entity = new ApplySerial_Entity();
        entity.setCustCode(custcode);
        model.addAttribute("applySerial_entity", entity);
        return "ClientInformation/ApplySerial";
    }

    @PostMapping("/ApplySerial")
    public String postApplySerial(Model model, @ModelAttribute ApplySerial_Entity applySerial_entity){

        return "ClientInformation/ApplySerial";
    }

//    //check insert
//    @ResponseBody
//    @RequestMapping(value = "/monitoring_insertCheck",method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
//    public String findAll(@RequestBody Map<String, Object> map){;
//        String bpm_no = map.get("bpm_no").toString();
//        insert_result = applySerial_service.insertCheck(bpm_no);
//        return insert_result;
//    }

    @ResponseBody
    @RequestMapping(value = "/ApplySerial/getAll", method = RequestMethod.GET)
    public JSONObject getBmpNo() {
        JSONObject result= new JSONObject();
        ApplySerial_Entity recordApplySerialEntity = applySerial_service.checkIsRecordUncompleted(custcode);
        if (recordApplySerialEntity == null || recordApplySerialEntity.getBPM_NO().equals("")) {
            if (recordApplySerialEntity == null)
                recordApplySerialEntity = new ApplySerial_Entity();
            recordApplySerialEntity.setProcessId(amountDeal_service.dealWithMoneyAmount(Integer.parseInt(applySerial_service.getPipelineNo()) + 1 + "", 6, 0));
            recordApplySerialEntity.setCustCode(custcode);
            User_Entity operator = user_service.getByUserId(operatorId);
            recordApplySerialEntity.setBankCode(operator.getBranch());
            recordApplySerialEntity.setOOUser(operator.getUsername());
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            recordApplySerialEntity.setStartDate(simpleDateFormat.format(date));
            recordApplySerialEntity.setLastSubmitDate(recordApplySerialEntity.getStartDate());
            recordApplySerialEntity.setStatus("A");
            StringBuffer Bmp_No = new StringBuffer("BP");
            Bmp_No.append(operatorBank);
            Bmp_No.append(amountDeal_service.dealWithMoneyAmount(Integer.parseInt(applySerial_service.getCustomerNum()) + 1 + "", 7, 0));
            recordApplySerialEntity.setBPM_NO(Bmp_No.toString());

            //html显示
            ApplySerial_Entity htmlResult = new ApplySerial_Entity();
            htmlResult.setBPM_NO(recordApplySerialEntity.getBPM_NO());
            htmlResult.setCustCode(recordApplySerialEntity.getCustCode());
            result = JSONObject.fromObject(htmlResult);
            //启动工作流
            JSONObject woekInfo = new JSONObject();
            woekInfo.put("TemplateName", "VillageBank");
            woekInfo.put("USERID", operatorId);
            woekInfo.put("TaskDesc", "test new lor Start Work");
            woekInfo.put("TaskName", "start test");
            String workFlowResultStr = workFlowService.StartWorkflow(woekInfo.toString());
//            System.out.println(JSONObject.fromObject(recordApplySerialEntity));
//            System.out.println(workFlowResultStr);
            //工作流列表信息
            String bpm_no = recordApplySerialEntity.getBPM_NO(); //贷款编号
            String processid = recordApplySerialEntity.getProcessId(); //运行ID
            String taskname = woekInfo.getString("TaskName"); //任务名称
            String initiatorname = woekInfo.getString("USERID"); //启动人
            String templatename = woekInfo.getString("TemplateName"); //模板名称
            String state = "Wait"; //状态
            String createtime = applySerial_service.getCreatetime(bpm_no); //创建时间
            //保存LoanRouteHistory
            JSONArray jsonArray = JSONArray.fromObject(workFlowResultStr);
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            if (jsonObject.get("isSuc").equals("true")) {
                //保存
                applySerial_service.insertRecord(recordApplySerialEntity);
                applySerial_service.startOrUpdateWorkFlow(operatorId, recordApplySerialEntity.getBPM_NO(), "进入流程申请", "1", jsonObject.getString("taskId"));
                if (insert_result != null)
                    if (insert_result.equals("0")) {
                        applySerial_service.saveWorkflowListInfo(bpm_no, processid, taskname, initiatorname, templatename, state, createtime); //保存工作流列表信息
                    } else {
                        applySerial_service.updateWorkflowListInfo(bpm_no, processid, taskname, initiatorname, templatename, state, createtime); //更新工作流列表信息
                    }
            } else {
                result = JSONObject.fromObject(recordApplySerialEntity);
            }
            return result;
        }
        result = JSONObject.fromObject(recordApplySerialEntity);
//        System.out.println(result.toString());
        return result;
    }

}
